import axios from 'axios'
import { MessageBox, Message } from '@/element'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
import vm from '@/main'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60 // request timeout
})

const errorStatuses = [401, 402, 403, 404]

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['WEB-TOKEN'] = getToken()
      config.headers['LANG'] =
        localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
      config.headers['time-zone'] =
        Intl.DateTimeFormat().resolvedOptions().timeZone
      config.headers['platCode'] = 'TOMS'
    }
    if (config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              const params = propName + '[' + key + ']'
              var subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000 && res.code !== 0) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    return res
    // }
  },
  (error) => {
    if (error.response != null) {
      const status = error.response.status
      const { traceId, code } = error.response.data
      if (status === 401) {
        store.dispatch('user/resetToken').then(() => {
          Message({
            message: 'You have been logged out,please log in again',
            type: 'error',
            duration: 5 * 1000
          })
        })
        router.replace('/login')
        return
      }
      let errorMessage
      if (error.response.data.message) {
        errorMessage = error.response.data.message
      } else {
        errorMessage = error.message
      }

      // 参数错误提示特殊处理
      if (status === 501) {
        if (error.response.data.message) {
          const paramResp = JSON.parse(error.response.data.message)
          errorMessage = paramResp.msg || paramResp.message
          // 特殊处理，后面2.1重构好要去除
          if (errorMessage.indexOf('task [] in plan mode') > 0) {
            errorMessage = errorMessage.replace(
              'task [] in plan mode',
              'a update schedule'
            )
          }
        } else {
          errorMessage = error.message
        }
      }

      if (status >= 500) {
        MessageBox.confirm(
          `<div class="content">${errorMessage}</div><p class="error__message">Error code: ${
            code + '-' || ''
          }${traceId || ''}</p>`,
          'Error',
          {
            confirmButtonText: 'OK',
            showCancelButton: false,
            type: 'error',
            center: false,
            dangerouslyUseHTMLString: true
          }
        )
        if (status !== 501) {
          return new Promise((resolve, reject) => {
            reject(error)
          })
        }
      } else if (errorStatuses.includes(status)) {
        Message({
          message: errorMessage,
          type: 'error',
          duration: 5 * 1000
        })
        return new Promise(() => {})
      }
    } else if (error.message.indexOf('timeout') !== -1) {
      Message({
        message: vm.$t('common.time_out'),
        type: 'error',
        duration: 5 * 1000
      })
      error.timeout = true
    }
    return Promise.reject(error.response ? error.response.data : error)
  }
)

export default service
